package com.jn.erp.wechat.common.config;

import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/9/9 11:32
 */
@RequiredArgsConstructor
@Configuration
public class WxCpConfiguration {

    private final WxCpConfig wxCpConfig;
    private static WxCpConfig configFromYml;


    @PostConstruct
    public void init() {
        if (wxCpConfig != null && StringUtils.isNotBlank(wxCpConfig.getCorpId())) {
            configFromYml = new WxCpConfig();
            BeanUtils.copyProperties(wxCpConfig, configFromYml);
        }

    }


    //用户同步
    @Bean
    public WxCpService wxCpUserService() {
        // 1. 创建WxCpConfigStorage对象
        WxCpDefaultConfigImpl wxCpConfigStorage = new WxCpDefaultConfigImpl();
        // 设置微信企业号的appId和secret
        wxCpConfigStorage.setCorpId(configFromYml.getCorpId());
        wxCpConfigStorage.setCorpSecret(configFromYml.getCorpUserSecret());
        WxCpService wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(wxCpConfigStorage);
        return wxCpService;
    }


    //用户同步
    @Bean
    public WxCpService wxCpSyncService() {
        // 1. 创建WxCpConfigStorage对象
        WxCpDefaultConfigImpl wxCpConfigStorage = new WxCpDefaultConfigImpl();
        // 设置微信企业号的appId和secret
        wxCpConfigStorage.setCorpId(configFromYml.getCorpId());
        wxCpConfigStorage.setAgentId(configFromYml.getAgentId());
        wxCpConfigStorage.setCorpSecret(configFromYml.getAgentCorpSecret());
        // 设置访问token和access token的获取方式（平台没有提供，需要自己实现）
        // 2. 创建WxCpService对象
        WxCpService wxCpService = new WxCpServiceImpl();
        // 3. 注入配置存储对象
        wxCpService.setWxCpConfigStorage(wxCpConfigStorage);
        return wxCpService;
    }


}
